package com.flute.tools.util.performance;

import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.flute.tools.util.StringUtil;

public class PerformanceTester {

	private PerformanceInfo info;
	private PerformanceResult result;

	public static void main(String[] args) throws InterruptedException {
		PerformanceTester tester = new PerformanceTester();
		if (args == null || args.length == 0) {
			args = new String[1];
			args[0] = PerformanceInfo.class.getResource("performance.xml")
					.getPath();
		}
		tester.setInfo(PerformanceInfo.fromFile(args[0]));
		tester.run();

		Thread.sleep(1000000000);
	}

	public PerformanceTester() {
	}

	public void run() {
		List<String> list = UrlSet.urlListFromFile(info.getPath());
		for (int i = 0; i < info.getThreadCount(); i++) {
			Thread th = new Thread(getRunnable(i, info.getExeTime(), list));
			th.start();
		}
	}

	private Runnable getRunnable(final int i, final int count,
			final List<String> list) {
		return new Runnable() {

			@Override
			public void run() {
				HttpClient httpclient = new DefaultHttpClient();
				synchronized (info) {
					if (result == null) {
						result = new PerformanceResult(info.getTimes().toArray(
								new Long[] {}), info.getPrintCount());
						if (info.getCollector() != null) {
							info.getCollector().getResult().setPrintCount(
									result.getPrintCount());
							info.getCollector().getResult().setTimes(
									result.getTimes());
						}
					}
				}
				for (int i = 0; i < count; i++) {
					runTest(httpclient);
				}
			}

			private void runTest(HttpClient httpclient) {
				for (int i = 0; i < list.size(); i++) {
					String url = list.get(Double.valueOf(
							Math.random() * list.size()).intValue());
					if (!StringUtil.isNullOrEmpty(url)) {
						long s = System.currentTimeMillis();
						try {
							HttpGet post = new HttpGet(url);

							HttpResponse respose = httpclient.execute(post);
							long e = System.currentTimeMillis();

							byte[] bs = EntityUtils.toByteArray(respose
									.getEntity());
							// System.out.println(bs.length);
							//
							String charset = EntityUtils
									.getContentCharSet(respose.getEntity());
							if (StringUtil.isNullOrEmpty(charset)) {
								charset = "utf-8";
							}
							String content = new String(bs, charset);

							if (info.getCollector() != null) {
								info.getCollector().getResult()
										.record(
												info.getCollector().getTime(
														content),
												respose.getStatusLine()
														.getStatusCode(),
												bs.length);

								info.getCollector().getResult().getCount();
							}
							result.record(e - s, respose.getStatusLine()
									.getStatusCode(), bs.length);

							result.getCount();
						} catch (Exception e) {
							long end = System.currentTimeMillis();
							result.record(end - s, -50, 0);
							e.printStackTrace();
						}
					}
				}
			}
		};
	}

	@SuppressWarnings("unused")
	private long getLong(String time) {
		time = time.replace("耗时：", "");

		return Long.valueOf(time);
	}

	public PerformanceInfo getInfo() {
		return info;
	}

	public void setInfo(PerformanceInfo info) {
		this.info = info;
	}
}
